package cc.lzmsh.job;

import cc.lzmsh.domain.entity.Article;
import cc.lzmsh.service.ArticleService;
import cc.lzmsh.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Author:   msh
 * Date:     2024/9/24 下午4:45
 * Description:
 */

@Component
public class UpdateViewCountJob {

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ArticleService articleService;

    @Scheduled(cron = "0/55 * * * * ?")
    public void updateViewCount() {
        Map<String, Integer> viewCountMap = redisCache.getCacheMap("article:viewCount");
        // 获取redis中的数据, 转换成Article对象
        List<Article> ArricleList = viewCountMap.entrySet().stream().map(entry ->
                new Article(Long.valueOf(entry.getKey()), entry.getValue().longValue())).collect(Collectors.toList());
        // 更新到数据库中
        articleService.updateBatchById(ArricleList);
    }
}
